﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Windows.Media.Imaging;
using GoogleWeather.GeocodeService;
using System.Collections.ObjectModel;
using System.Device.Location;
using Microsoft.Phone.Controls.Maps;

namespace GoogleWeather
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        private void btnGo_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (txtCity.Text.Trim() == string.Empty)
                return;

            WebClient client = new WebClient();
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
            client.OpenReadAsync(new Uri("http://www.google.com/ig/api?weather=" + txtCity.Text));

            BingSetMap();
        }

        private void BingSetMap()
        {
            GeocodeRequest geocodeRequest = new GeocodeRequest();
            geocodeRequest.Credentials = new Credentials();
            geocodeRequest.Credentials.ApplicationId = "<Your Bing Map Id>";

            geocodeRequest.Query = txtCity.Text;

            FilterBase[] filters = new FilterBase[1];
            filters[0] = new ConfidenceFilter() { MinimumConfidence = Confidence.High };

            GeocodeOptions geocodeOptions = new GeocodeOptions();
            geocodeOptions.Filters = new ObservableCollection<FilterBase>(filters);
            geocodeRequest.Options = geocodeOptions;

            GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
            geocodeService.GeocodeCompleted += new EventHandler<GeocodeCompletedEventArgs>(geocodeService_GeocodeCompleted);
            geocodeService.GeocodeAsync(geocodeRequest);
        }

        void geocodeService_GeocodeCompleted(object sender, GeocodeCompletedEventArgs e)
        {
            GeocodeResponse geocodeResponse = e.Result;
            GeoCoordinate geoCoordinate = new GeoCoordinate();
            geoCoordinate.Latitude = geocodeResponse.Results[0].Locations[0].Latitude;
            geoCoordinate.Longitude = geocodeResponse.Results[0].Locations[0].Longitude;
            bingMapItem.SetView(geoCoordinate, 10);
        }

        void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            Stream stream = e.Result;
            XDocument xDoc = XDocument.Load(stream);
            pivotWeather.SelectedIndex = 1;
            GetCurrentWeather(xDoc);
            GetForeCast(xDoc);
        }

        private void GetCurrentWeather(XDocument xDoc)
        {
            try
            {
                List<WeatherReport> lstWeatherReport = new List<WeatherReport>();

                string city = xDoc.Descendants("forecast_information").First().Element("city").Attribute("data").Value;
                string url = "http://www.google.com" + xDoc.Descendants("current_conditions").First().Element("icon").Attribute("data").Value;

                lstWeatherReport = (from item in xDoc.Descendants("current_conditions")
                                    select new WeatherReport()
                                    {
                                        DayOfWeek = "Today",
                                        City = city,
                                        //WeatherImage = img,
                                        Condition = item.Element("condition").Attribute("data").Value,
                                        //TempF = item.Element("temp_f").Attribute("data").Value,
                                        TempC = item.Element("temp_c").Attribute("data").Value + " C",
                                        Humidity = item.Element("humidity").Attribute("data").Value,
                                        //ImageURL = item.Element("icon").Attribute("data").Value,
                                        Wind = item.Element("wind_condition").Attribute("data").Value
                                    }).ToList();

                lstWeather.ItemsSource = lstWeatherReport;
            }
            catch
            {
                lstWeather.ItemsSource = null;
            }
        }

        private void GetForeCast(XDocument xDoc)
        {
            try
            {
                List<WeatherReport> lstWeatherReport = new List<WeatherReport>();
                string city = xDoc.Descendants("forecast_information").First().Element("city").Attribute("data").Value;

                lstWeatherReport = (from item in xDoc.Descendants("forecast_conditions")
                                    select new WeatherReport()
                                    {
                                        DayOfWeek = item.Element("day_of_week").Attribute("data").Value,
                                        City = city,
                                        //WeatherImage = img,
                                        Condition = item.Element("condition").Attribute("data").Value,
                                        TempF = item.Element("low").Attribute("data").Value + " F",
                                        TempC = item.Element("high").Attribute("data").Value + " F"
                                    }).ToList();

                lstForecast.ItemsSource = lstWeatherReport;
            }
            catch
            {
                lstForecast.ItemsSource = null;
            }
        }

    }
}